package com.ftg.wymall.rabbit.chapter04;

import com.rabbitmq.client.*;

/**
 * 路由模式 ...
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/11/30 上午9:00
 */
public class PublishSending {

    public static void main(String[] args) {
        System.out.println("路由发送");
        // 1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 2.设置连接工厂的相关参数
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 3.创建连接
        try (Connection connection = connectionFactory.newConnection()) {
            Channel channel = connection.createChannel();
            // 4.创建交换机
            channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

            AMQP.Queue.DeclareOk declareOk = channel.queueDeclare("", false, true, false, null);


            for (int i = 0; i < 100; i++) {
                /**
                 * 绑定队列和交换机
                 * 参数1：队列名称
                 * 参数2：交换机名称
                 * 参数3：路由键
                 */
                String routerKey = "black" + (i % 2 == 0 ? 1 : 2);
                channel.queueBind(declareOk.getQueue(), "direct_logs", routerKey);
                String message = "Hello RabbitMQ 信息 -- " + i;
                channel.basicPublish("direct_logs", routerKey, null, message.getBytes());
                Thread.sleep(1000);
                System.out.println(" [x] Sent '" + message + "'");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
